package com.gjr.eduservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.gjr.commonutils.Result;
import com.gjr.eduservice.client.VodClient;
import com.gjr.eduservice.entity.EduVideo;
import com.gjr.eduservice.service.EduVideoService;
import com.gjr.servicebase.exceptionhandler.GuliException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 课程视频（课程小节） 前端控制器
 * </p>
 *
 * @author gjr
 * @since 2022-09-01
 */
@CrossOrigin
@RestController
@RequestMapping("/eduservice/video")
public class EduVideoController {

    @Autowired
    private EduVideoService eduVideoService;
    @Autowired
    private VodClient vodClient;

    /**
     * 根据小节id查询小节信息
     *
     * @param videoId 小节id
     * @return 小节对象
     */
    @GetMapping("/getVideo/{videoId}")
    public Result<?> addVideo(@PathVariable String videoId) {
        EduVideo video = eduVideoService.getOne(new LambdaQueryWrapper<EduVideo>()
                .eq(EduVideo::getId, videoId), false);
        return Result.ok().data("video", video);
    }

    /**
     * 添加小节
     *
     * @param eduVideo 小节对象
     * @return 返回值
     */
    @PostMapping("/addVideo")
    public Result<?> addVideo(@RequestBody EduVideo eduVideo) {
        eduVideoService.save(eduVideo);
        return Result.ok();
    }

    /**
     * 删除小节
     *
     * @param id 小节id
     * @return 返回值
     */
    @DeleteMapping("/{id}")
    public Result<?> deleteVideo(@PathVariable String id) {
        // 根据小节id获取视频id，调用方法实现视频删除
        EduVideo video = eduVideoService.getById(id);
        String videoSourceId = video.getVideoSourceId();
        // 当小节中存在视频才删除
        if (StringUtils.isNotEmpty(videoSourceId)) {
            // 删除阿里云端视频
            Result<?> result = vodClient.removeAlyVideo(videoSourceId);
            if (20001 == result.getCode()) {
                throw new GuliException(20001, "删除视频失败，熔断器......");
            }
        }

        // 删除小节
        eduVideoService.removeById(id);
        return Result.ok();
    }

    /**
     * 修改小节
     *
     * @param eduVideo 小节对象
     * @return 返回值
     */
    @PostMapping("/updateVideo")
    public Result<?> updateVideo(@RequestBody EduVideo eduVideo) {
        eduVideoService.updateById(eduVideo);
        return Result.ok();
    }
}

